package com.rnd.kx.mvp.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewConfigurationCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.rnd.kx.mvp.R;
import com.rnd.kx.mvp.bean.IndexBean;

import java.time.temporal.ValueRange;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class IndexAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private IndexBean indexBean;
    private Context context;
    private ImageLoader imageLoader;

    private static final int TYPE_BANNER = 0;
    private static final int TYPE_CATES = 1;
    private static final int TYPE_ARTICLE = 2;
    private int lastPosition;
    private int playPosition = 0;

    public IndexAdapter(IndexBean indexBean, Context context, ImageLoader imageLoader) {
        this.indexBean = indexBean;
        this.context = context;
        this.imageLoader = imageLoader;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0){
            return TYPE_BANNER;
        }else if (position == 1){
            return TYPE_CATES;
        }else if (position == 2){
            return TYPE_ARTICLE;
        }
        return 0;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_BANNER){
            View view = LayoutInflater.from(context).inflate(R.layout.item_index1, parent, false);
            return new ViewHolder0(view);
        }else if (viewType == TYPE_CATES){
            View view = LayoutInflater.from(context).inflate(R.layout.item_index2, parent, false);
            return new ViewHolder1(view);
        }else if (viewType == TYPE_ARTICLE){
            View view = LayoutInflater.from(context).inflate(R.layout.item_index3, parent, false);
            return new ViewHolder2(view);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ViewHolder0){
            final List<IndexBean.AdvBean> adv = indexBean.getAdv();
            BannerAdapter bannerAdapter = new BannerAdapter(adv, context,imageLoader);
            ((ViewHolder0) holder).viewPager.setAdapter(bannerAdapter);
            ((ViewHolder0) holder).viewPager.setCurrentItem(50000);
            if (((ViewHolder0) holder).all_point.getChildCount() != 0){
                //初始化控件时，设置第一个小圆点选中
                ((ViewHolder0) holder).all_point.getChildAt(0).setEnabled(true);
                lastPosition = 0;
                return;
            }else {
                for (int i = 0;i < adv.size();i++){
                    //加小白点，指示器（小圆点定义在drawable下的选择器，也可用小图片代替）
                    View pointView = new View(context);
                    pointView.setBackgroundResource(R.drawable.banner_point_selector);
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(20, 20);
                    if (i != 0){
                        layoutParams.leftMargin = 10;
                    }
                    pointView.setEnabled(false);
                    ((ViewHolder0) holder).all_point.addView(pointView,layoutParams);
                }
            }

            ((ViewHolder0) holder).all_point.getChildAt(0).setEnabled(true);
            lastPosition = 0;

            ((ViewHolder0) holder).viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int i, float v, int i1) {

                }

                @Override
                public void onPageSelected(int i) {
                    int newPosition = i % adv.size();
                    //设置小圆点为高亮或暗色
                    ((ViewHolder0) holder).all_point.getChildAt(newPosition).setEnabled(true);
                    ((ViewHolder0) holder).all_point.getChildAt(lastPosition).setEnabled(false);
                    lastPosition = newPosition;
                }

                @Override
                public void onPageScrollStateChanged(int i) {

                }
            });

            ViewConfiguration configuration = ViewConfiguration.get(context);
            final int touchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
            ((ViewHolder0) holder).viewPager.setOnTouchListener(new View.OnTouchListener() {
                int flage = 0;
                float x = 0, y = 0;
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()){
                        case MotionEvent.ACTION_DOWN:
                            flage=0;
                            x = event.getX();
                            y = event.getY();
                            Log.d("CSDTouch","按下");
                            break;

                        case MotionEvent.ACTION_MOVE:
                            float xDiff = Math.abs(event.getX() - x);
                            float yDiff = Math.abs(event.getY() - y);
                            if (xDiff < touchSlop && xDiff >= yDiff)
                                flage = 0;
                            else
                                flage = -1;
                            Log.d("CSDTouch","滑动");
                            break;

                        case MotionEvent.ACTION_UP:
                            Log.d("CSDTouch","抬起");
                            if (flage==0){
                                Intent intent;
                               /* int item=headViewPager.getCurrentItem();
                                String type = advBeans.get(item % advBeans.size()).getType();
                                if (type.equals("111")){//TODO:跳转食谱详情
                                    intent= new Intent(getContext(), RecipeDetailsActivity.class);
                                    intent.putExtra("id",advBeans.get(item%advBeans.size()).getId());
                                    getActivity().startActivity(intent);
                                }else if (type.equals("112")){//TODO:跳转商品详情
                                    intent= new Intent(getContext(), Detail2Activity.class);
                                    intent.putExtra("ID",advBeans.get(item%advBeans.size()).getId());
                                    intent.putExtra("topic_type","12");
                                    getActivity().startActivity(intent);
                                }else if (type.equals("113")){//TODO:跳转通用文章详情
                                    intent = new Intent(getContext(), ArticleDetailActivity.class);
                                    intent.putExtra("ID",advBeans.get(item%advBeans.size()).getId());
                                    intent.putExtra("topic_type","16");
                                }else if (type.equals("114")){//TODO:跳转教学视频详情
                                    intent = new Intent(getContext(), SuperLabDetailsActivity.class);
                                    intent.putExtra("id",advBeans.get(item%advBeans.size()).getId());
                                }else if (type.equals("115")){//TODO:跳转设备详情
                                    intent = new Intent(getContext(), ProductActivity.class);
                                    intent.putExtra("id",advBeans.get(item%advBeans.size()).getId());
                                }*/
                                Log.d("CSDTouch","点击跳转");
                            }
                            Log.d("CSDTouch","移动");
                            break;
                    }
                    return false;
                }
            });

        }else if (holder instanceof ViewHolder1){
            List<IndexBean.CatesBean> cates = indexBean.getCates();
            IndexCatesAdapter indexCatesAdapter = new IndexCatesAdapter(cates, context);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            ((ViewHolder1) holder).recyclerView.setLayoutManager(linearLayoutManager);
            ((ViewHolder1) holder).recyclerView.setAdapter(indexCatesAdapter);
        }else if (holder instanceof ViewHolder2){
            List<IndexBean.ArticleBean> article = indexBean.getArticle();
            final IndexArticleAdapter indexArticleAdapter = new IndexArticleAdapter(article, context);
            final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            ((ViewHolder2) holder).recyclerView.setLayoutManager(linearLayoutManager);
            ((ViewHolder2) holder).recyclerView.setAdapter(indexArticleAdapter);

            ((ViewHolder2) holder).recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {


                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                }

                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    recyclerView.getBaseline();
                    if (linearLayoutManager != null){
                        int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition();
                        View firstView = linearLayoutManager.findViewByPosition(firstVisibleItemPosition);
                        if (null != firstView){
                            if (dy > 0){
                                if (firstView.getHeight() + firstView.getTop() <= firstView.getHeight() / 3){
                                    if (linearLayoutManager.getChildCount() < 2){
                                        return;
                                    }
                                    if (playPosition == firstVisibleItemPosition + 1){
                                        return;
                                    }
                                    playPosition = firstVisibleItemPosition + 1;
                                    indexArticleAdapter.setPlay(playPosition);
                                }else {
                                    if (playPosition == firstVisibleItemPosition) {
                                        return;
                                    }
                                    playPosition = firstVisibleItemPosition;
                                    indexArticleAdapter.setPlay(playPosition);
                                }
                            }
                            if (dy < 0) {
                                if (firstView.getHeight() + firstView.getTop() >= firstView.getHeight() * 2 / 3) {
                                    //video stop or play second
                                    if (linearLayoutManager.getChildCount() < 2) {
                                        return;
                                    }
                                    if (playPosition == firstVisibleItemPosition) {
                                        return;
                                    }
                                    playPosition = firstVisibleItemPosition;
                                    indexArticleAdapter.setPlay(playPosition);
                                } else {
                                    if (playPosition == firstVisibleItemPosition + 1) {
                                        return;
                                    }
                                    playPosition = firstVisibleItemPosition + 1;
                                    indexArticleAdapter.setPlay(playPosition);
                                }
                            }

                        }
                    }
                }
            });

        }
    }

    @Override
    public int getItemCount() {
        return 3;
    }

    public class ViewHolder0 extends RecyclerView.ViewHolder{

        @BindView(R.id.viewpager)
        ViewPager viewPager;
        @BindView(R.id.item_index1_all_point)
        LinearLayout all_point;

        public ViewHolder0(View itemView) {
            super(itemView);
            ButterKnife.bind(this,itemView);
        }
    }

    public class ViewHolder1 extends RecyclerView.ViewHolder{

        @BindView(R.id.item_index2_recyclerview)
        RecyclerView recyclerView;
        public ViewHolder1(View itemView) {
            super(itemView);
            ButterKnife.bind(this,itemView);
        }
    }

    public class ViewHolder2 extends RecyclerView.ViewHolder{

        @BindView(R.id.item_index3_recyclerview)
        RecyclerView recyclerView;
        public ViewHolder2(View itemView) {
            super(itemView);
            ButterKnife.bind(this,itemView);
        }
    }

}
